<?php
/** 
 * GZHandler class
 * This class is used to handle output into gzip if browser accept
 *
 * @author Patrice Ferlet <metal3d@copix.org> 
 * @package utils
 * @license http://opensource.org/licenses/lgpl-3.0.html GNU Lesser General Public License Version 3.0 (LGPLv3)
 */
class PGZHandler {

    static $_instance = NULL;
    static $cmd = NULL;

    private function __construct(){
       PGZHandler::$cmd =  _config()->get('root/path')->name('gzipcmd');
    }

    public function instance(){
        if(PGZHandler::$_instance === NULL){
            PGZHandler::$_instance = new PGZHandler();
        }
        return PGZHandler;
    }

    public function encode($string){
        $string = str_replace('"','\"',$string);
        $string = str_replace('$','\$',$string);
        $com = str_replace('__','"'.$string.'"',PGZHandler::$cmd);
        $proc = popen($com,'r');
        $out = "";

        while ($line = fread($proc,1024)){
            $out.=$line;
        }
        fclose($proc);
        return $out;
    }

    public function out($output){
        if (isset($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos($_SERVER['HTTP_ACCEPT_ENCODING'],'gzip') !== FALSE){
            $output = PGZHandler::encode($output);
            header('Content-Encoding: gzip');
        }
        echo $output;
    }
}
